package com.fengchao.util.wechat.pay;

import com.alibaba.fastjson.JSON;
import com.fengchao.api.config.Constant;
import com.fengchao.util.net.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.fengchao.util.wechat.pay.SignUtil.createSign;

/**
 * Created by http://my.oschina.net/wangnian on 2016/8/4.
 */
public class WeixinPay {


    private static Logger logger = LoggerFactory.getLogger(WeixinPay.class);

    /**
     * 统一下单
     *
     * @param orderSn
     * @param totalFee
     * @param spBillCreateIP
     * @return
     */
    public static Map<Object, Object> sendWxPayRequest(String orderSn, String totalFee, String spBillCreateIP) {
        //签名
        SortedMap<Object, Object> parameters = new TreeMap<>();
        parameters.put("appid", Constant.APPID);
        parameters.put("body", Constant.ORDER_NAME);
        parameters.put("mch_id", Constant.MCH_ID);
        parameters.put("nonce_str", String.valueOf(new Date().getTime()));
        parameters.put("notify_url", Constant.CONFIGMAP.get("weixin.asynchronousNotifyUrl"));
        parameters.put("out_trade_no", orderSn);
        parameters.put("spbill_create_ip", spBillCreateIP);
        parameters.put("total_fee", totalFee);
        parameters.put("trade_type", "APP");
        String sign = createSign("utf-8", parameters);
        //请求xml参数
        StringBuffer requestStr = new StringBuffer("<xml>");
        requestStr.append("<appid><![CDATA[");
        requestStr.append(parameters.get("appid"));
        requestStr.append("]]></appid>");
        requestStr.append("<body><![CDATA[");
        requestStr.append(parameters.get("body"));
        requestStr.append("]]></body>");
        requestStr.append("<mch_id><![CDATA[");
        requestStr.append(parameters.get("mch_id"));
        requestStr.append("]]></mch_id>");
        requestStr.append("<nonce_str><![CDATA[");
        requestStr.append(parameters.get("nonce_str"));
        requestStr.append("]]></nonce_str>");
        requestStr.append("<notify_url><![CDATA[");
        requestStr.append(parameters.get("notify_url"));
        requestStr.append("]]></notify_url>");
        requestStr.append("<out_trade_no><![CDATA[");
        requestStr.append(parameters.get("out_trade_no"));
        requestStr.append("]]></out_trade_no>");
        requestStr.append("<spbill_create_ip><![CDATA[");
        requestStr.append(parameters.get("spbill_create_ip"));
        requestStr.append("]]></spbill_create_ip>");
        requestStr.append("<total_fee><![CDATA[");
        requestStr.append(parameters.get("total_fee"));
        requestStr.append("]]></total_fee>");
        requestStr.append("<trade_type><![CDATA[");
        requestStr.append(parameters.get("trade_type"));
        requestStr.append("]]></trade_type>");
        requestStr.append("<sign><![CDATA[");
        requestStr.append(sign);
        requestStr.append("]]></sign>");
        requestStr.append("</xml>");
        try {
            String body = HttpUtil.post(Constant.ORDER_URL, requestStr.toString());
            String resultStr = new String(body.getBytes("ISO-8859-1"), "utf-8");
            SortedMap<Object, Object> resultMap = XMLUtil.doXMLParse(resultStr);
            logger.info("微信统一下单响应参数= {}", JSON.toJSON(resultMap));
            if (Constant.SUCCESS.equals(resultMap.get("result_code"))) {
                String package1 = "Sign=WXPay";
                SortedMap<Object, Object> payParameters = new TreeMap<>();
                payParameters.put("appid", Constant.APPID);
                payParameters.put("partnerid", Constant.MCH_ID);
                payParameters.put("prepayid", resultMap.get("prepay_id"));
                payParameters.put("package", package1);
                payParameters.put("noncestr", String.valueOf(new Date().getTime()));
                payParameters.put("timestamp", new Date().getTime() / 1000);
                String paySign = SignUtil.createSign("utf-8", payParameters);
                payParameters.put("sign", paySign.toUpperCase());
                return payParameters;
            } else {
                logger.warn("微信统一下单错误:{}", JSON.toJSON(resultMap));
            }
            return null;
        } catch (Exception ex) {
            logger.warn("微信统一下单异常 ex:", ex);
        }
        return null;
    }
}
